/**
 * Created by tdzl2003 on 8/22/16.
 */
import config from '../../config/ronglian.json';


import crypto from 'crypto';
import request from 'request';
import moment from 'moment';

function hmac(buf, key) {
  return crypto.createHmac('sha1', key).update(buf).digest();
}

function md5(buf) {
  return crypto.createHash('md5').update(buf).digest('hex');
}

function base64(buffer) {
  return buffer.toString('base64');
}

function makeAuth(account, token) {
  let timestamp = moment().format('YYYYMMDDHHmmss'), sig = account + token + timestamp, auth = account + ':' + timestamp;
  sig = md5(sig).toUpperCase();
  auth = base64(new Buffer(auth));
  return {sig, auth};
}

export function sendSMS(mobile, code, min) {
  const {templateId, restUrl, softVer, mainAccount, mainToken, appId} = config;
  const {sig, auth} = makeAuth(mainAccount, mainToken);
  const url = `${restUrl}/${softVer}/Accounts/${mainAccount}/SMS/TemplateSMS?sig=${sig}`;
  // console.log('p', url, auth, mobile, appId, code, min);

  let form = {
    to: mobile,
    appId,
    templateId: templateId,
    datas: [code, min],
  };

  form = JSON.stringify(form);

  request({
    url,
    method: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': auth,
    },
    body : form,
  }, function(error, response, body) {
    if (error){
      console.error(error);
    }
    if (__DEV__) {
      console.log('res', response, error, body);
    }
    if ('000000' === response.statusCode) {

    }
  });
}